//
//  HMEmoticonView.swift
//  WeiBo
//
//  Created by apple on 16/7/2.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

let HMEmoticonViewReuseIdentifier = "HMEmoticonViewReuseIdentifier  "

class HMEmoticonView: UIView {

    // 第一步 -- 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        setupCollectionView()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步 -- 定义一个方法,来实现 视图的添加和布局
    private func setupUI(){
        
        backgroundColor = RandomColor()
        // 在这里判断一下版本,如果手机的系统是 9.0以上的,我们addsubView就是StuckView
        
        addSubview(collectionView)
        addSubview(emoticonToolBarView)
        
        // 设置约束
        emoticonToolBarView.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(self.snp_left)
            make.bottom.equalTo(self.snp_bottom)
            make.right.equalTo(self.snp_right)
            
            make.height.equalTo(44)
            
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.snp_left)
            make.top.equalTo(self.snp_top)
            make.right.equalTo(self.snp_right)
            
            make.bottom.equalTo(emoticonToolBarView.snp_top)
            
        }
        
    }
    
    //MARK:-- 设置UICollectionView的属性
    private func setupCollectionView(){
        
        collectionView.registerClass(HMEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: HMEmoticonViewReuseIdentifier)
        
        collectionView.dataSource = self
        
        // 设置导航的条隐藏
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        // 设置分页
        collectionView.pagingEnabled = true
        
        // 遇到问题一定要把问题描绘清楚,然后定位到大概的位置,打断点或者 NSLog
        
//        print(collectionView.bounds.size)
//        // 设置layout
//        flowLayout.itemSize = collectionView.bounds.size
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        
        // 设置滚动的方向
        flowLayout.scrollDirection = .Horizontal
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    <#code to be executed after a specified delay#>
//});
         // 让CollectionView滚到 默认
        // 时机的问题
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.025)), dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
        
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
//         print(collectionView.bounds.size)
        // 设置layout
        flowLayout.itemSize = collectionView.bounds.size
    }
    
    // 第三步: 懒加载控件
    
    // 设置流水布局
    private var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    // UICollectionView
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.flowLayout)
    
    // 底部视图
    private lazy var emoticonToolBarView: HMEmoticonToolBarView = {
    
        let toolBarView = HMEmoticonToolBarView(frame: CGRectZero)
        
        toolBarView.delegate = self
        
        return toolBarView
    }()
    
    
}

extension HMEmoticonView: UICollectionViewDataSource,HMEmoticonToolBarViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HMEmoticonManager.getAllEmoticon().count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonManager.getAllEmoticon()[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMEmoticonViewReuseIdentifier, forIndexPath: indexPath) as! HMEmoticonCollectionViewCell
        
        
//        cell.label.text = "第\(indexPath.section)部分, 第\(indexPath.item)页"
        cell.emoticons = HMEmoticonManager.getAllEmoticon()[indexPath.section][indexPath.item]
        
        return cell
    }
    
    func emoticonButtonClick(type: HMEmoticonType) {
        
        switch type {
            
        case .Recent: collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Default:collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 1), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Emoji: collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 2), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        case .Lxh : collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 3), atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        }
        
    }
}

class HMEmoticonCollectionViewCell: UICollectionViewCell {
    
    var emoticons: [HMEmoticon]?{
    
        didSet{
        
            // 让表情先隐藏,需要使用的时候,再显示出来
            for button in emoticonsButton{
                button.hidden = true
            }
            
            // 对数据进行遍历.有多少个数据,就应该有多少个表情
            for (index,emoticon) in emoticons!.enumerate() {
                
                // 1. 首先拿出Cell里对应的按钮
                let button = emoticonsButton[index]
                
                // 赋值
                button.emoticon = emoticon
                
                // 让按钮显示
                button.hidden = false
                
                
//                // 2. 赋值 -- 测试
////                button.setTitle(emoticon.chs, forState: UIControlState.Normal)
//                // 如何区分 图片表情以及 emoji? 我们可以通过对象里 emoji 与 png 为空的情况去区分
//                if let png = emoticon.png,path = emoticon.path {
//                    // 图片表情
//                    // /Users/apple/Library/Developer/CoreSimulator/Devices/C4B16C32-00BA-46B4-880F-8A0ECCA1DE13/data/Containers/Bundle/Application/9886DC31-6F15-4FA0-B191-C728BF124C0A/WeiBo.app/Emoticons.bundle/com.sina.default\")/Optional(\"d_zuiyou.png\")
//                    let imageName = "\(path)/\(png)"
//                    button.setImage(UIImage(named: imageName), forState: UIControlState.Normal)
//                    
//                } else {
//                    // 一定要注意cell的重用
//                    button.setImage(nil, forState: UIControlState.Normal)
//                    
//                }
//                
//                
//                if let emoji = emoticon.emoji {
//                    
//                    // emoji
//                    button.setTitle(emoji, forState: UIControlState.Normal)
//                } else {
//                    
//                    // 还是由于cell的重用
//                    button.setTitle(nil, forState: UIControlState.Normal)
//                }
            }
            
        }
        
    }
    
    // 定义一个数组,来保存20个按钮
    private lazy var emoticonsButton: [HMEmoticonButton] = [HMEmoticonButton]()
    
    // 第一步 -- 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步 -- 定义一个方法,来实现 视图的添加和布局
    private func setupUI(){
        
        backgroundColor = RandomColor()
        
//       contentView.addSubview(label)
//        
//        label.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(contentView.snp_center)
//        }
        // cell是存在重用的
        addChildButton()
        
        
       
        
    }
    
    //MARK:-- 添加20个button,到cell里
    private func addChildButton(){
        
        // 设置button的宽和高
        let childButtonW: CGFloat = bounds.width / 7
        let childButtonH: CGFloat = bounds.height / 3
        
        for i in 0..<20 {
            
            let button = HMEmoticonButton()
            
            // 为了区分按钮,我们给按钮设置一个title
//            button.setTitle("\(i)", forState: UIControlState.Normal)
            
            let col = i % 7
            let row = i / 7
            
            button.frame = CGRectMake(CGFloat(col) * childButtonW, CGFloat(row) * childButtonH, childButtonW, childButtonH)
            
            // 设置button的其他属性
            button.titleLabel?.font = UIFont.systemFontOfSize(32)
            
            // 添加点击事件
            button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            // 添加到contentView
            contentView.addSubview(button)
            
            // 把按钮添加到数组里
            emoticonsButton.append(button)
        }
        
        // 添加删除按钮
        
        deleteButton.frame = CGRectMake(bounds.width - childButtonW, bounds.height - childButtonH, childButtonW, childButtonH)
        contentView.addSubview(deleteButton)
        
        
    }
    
    //MARK:-- 按钮的点击事件
    @objc private func childButtonClick(button: HMEmoticonButton){
        
        // 最近里要显示我点击的表情
        // 最近表情需要 HMEmoticon 对象
        
//        button.emoticon
        
        guard let emoticon = button.emoticon else {
            return
        }
        
      HMEmoticonManager.addRecentEmoticon(emoticon)
        
        
        // 发送一个通知,给HMPublishViewController
        // 通知传递的参数,不要放在 object,object是谁发送的通知
        // userInfo 才是传递参数
        NSNotificationCenter.defaultCenter().postNotificationName(kNoitficationTransformEmoticon, object: nil, userInfo: ["emoticon": emoticon])
        
        
    }
    
    @objc private func deleteButtonClick(button: UIButton){
        
        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationDeleteEmotiocn, object: nil)
        
        
    }
    
    // 第三步: 懒加载控件
    // 测试使用label
    private lazy var label: UILabel = UILabel()
    
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted" ), forState: .Highlighted)
        
        button.addTarget(self, action: "deleteButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
}
